<template>
    <div class="home" :class="{ 'main-transparent' : user.getPanel() === 'true' }">
        <!-- 工具栏 --> 
        <div class="toolbar-wrap" v-show="!preview && !webVisible">
            <Toolbar></Toolbar>
        </div>
        <div class="content-wrap" v-show="!preview && !webVisible">
            <!-- 图层 -->
            <div class="page-wrap">
                <div class="page-tab">
                    <div :class="tabVisible === 'layer' ? 'active' : ''" @click="pageTab('layer')">图层</div>
                    <div :class="tabVisible === 'history' ? 'active' : ''" @click="pageTab('history')">操作记录</div>
                </div>
                <div v-show="tabVisible === 'layer'">
                    <Page></Page>
                    <Layer></Layer>
                </div>
                <div v-show="tabVisible === 'history'">
                    <History></History>
                </div>
                <div class="page-bottom-warp">
                    剪切板: 已复制个{{ shortcut.getCurrentElementList().length }}组件&nbsp;&nbsp;&nbsp;&nbsp;<span class="remove-copy" @click="shortcut.cleanCurrentElementList()">清除</span>
                </div>
            </div>
            <!-- 画布区域 -->
            <div class="main-wrap" :class="{ 'main-transparent' : user.getPanel() === 'true' }">
                <div class="content" ref="SECTION_CONTENT" :id="window.getRootName() + 'SECTION_CONTENT'">
                    <div class="content-editor" :id="window.getRootName() + 'SECTION_CONTENT_EDITOR'" ref="mainCanvas" @scroll.passive="getScroll" @mousedown="shadeMouseDown">
                        <Main :preview="preview"></Main>
                    </div>
                    <div class="horizontal-rule" ref="horizontalRule" :style="{'left': (scroll.left) + 'px'}">
                        <ScaleRule mode="horizontal"></ScaleRule>
                    </div>
                    <div class="vertical-rule" ref="verticalRule" :style="{'top': (scroll.top) + 'px'}">
                        <ScaleRule mode="vertical"></ScaleRule>
                    </div>
                </div>
            </div>
            <!-- 右侧属性 -->
            <div class="attribute-wrap">
                <Attribute></Attribute>
            </div>
        </div>
        <div class="preview" :class="{ 'main-transparent' : user.getPanel() === 'true' }" v-if="preview">
            <Preview :elementList="elementList" :canvas="canvas" :pageList="pageList"></Preview>
            <div class="close-button" @click="bus.setPreview(false);">
                <i class="el-icon-close"></i>
            </div>
        </div>
        <Editor></Editor>
        <Coder></Coder>
        <div class="interactive-tab" v-if="user.getPanel() === 'true' && !preview">
            <div class="interactive-tab-top" :class="{ 'active-visible': navbar === 0 }">
                <!-- <img src="../../image/main/toolbar/logo_dts.svg" /> -->
            </div>
            <div class="interactive-tab-bottom">
                <span :class="{ active: navbar === index }" v-for="(item, index) in tabList" :key="index" @click="barClick(index)">{{ item.name }}</span>
            </div>
        </div>
        
        <el-dialog title="" :visible.sync="warningFontVisible" width="435px" top="35vh" class="review-dialog-no-t" :close-on-click-modal="false">
            <div class="dialog-content">
                <img src="../../image/main/toolbar/icon_Warning.svg" alt="">
                <div class="dialog-content-c">
                    <p class="t">缺少字体</p>
                    <p class="b">某些文本对象的包含的字体丢失<br/>请安装相应字体或替换字体以编辑文本</p>
                </div>
            </div>
            <span slot="footer">
                <div class="share-btn" @click="warningFontVisible = false">知道了</div>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import store from '@/js/store/state.js';
import history from '@/js/main/history.js';
import template from '@/js/element/template.js';
import status from '@/js/main/status.js';
import bus from '@/js/event/bus.js';
import color from '@/js/main/color.js';
import line from '@/js/main/line.js';
import request from '@/js/util/url.js';
import user from '@/js/util/user.js';
import shortcut from '@/js/main/shortcut.js';
import message from '@/js/util/message.js';
import scene from '@/js/main/scene.js';
import { getFontList, getTemplateList } from '@/js/util/api.js';
import tree from '@/js/main/tree.js';
import { mapGetters } from "vuex";

export default {
    data() {
        return {
            window: window,
            bus: bus,
            status: status,
            shortcut: shortcut,
            canvas: {},
            preview: false,
            elementList: [],
            pageList: [],
            layout: this.$route.query.layout,
            tabVisible: 'layer',
            user: user,
            tabList: [
                {
                    name: '场景'
                },
                {
                    name: '大屏'
                }
            ],
            navbar: 1,
            webVisible: false,
            scroll: {
                top: 20,
                left: 20
            },
            notFontList: [],
            warningFontVisible: false
        };
    },
    components: {
        Toolbar: () => import('@/view/main/Toolbar.vue'),
        Page: () => import('@/view/main/Page.vue'),
        Main: () => import('@/view/main/Main.vue'),
        ScaleRule: () => import('@/view/component/ScaleRule.vue'),
        Attribute: () => import('@/view/main/Attribute.vue'),
        Layer: () => import('@/view/main/Layer.vue'),
        History: () => import('@/view/main/History.vue'),
        Preview: () => import('@/view/main/Preview.vue'),
        Editor: () => import('@/view/main/editor/Editor.vue'),
        Coder: () => import('@/view/main/editor/Coder.vue')
    },
    computed: {
        ...mapGetters(["mapActive"]),
    },
    mounted() {
        history.initialize();
        template.initialize();
        template.message = function(str, type) {
            message.message(str, type);
        };
        line.initialize();
        bus.on('setPreview', this.setPreview);
        color.resetCustomColorList();
        this.initialize();
        this.autoCanvasScale();
        this.apiInit();
    },
    destroyed() {
        bus.off('setPreview', this.setPreview);
    },
    methods: {
        apiInit() {
            this.notFontList = [];
            let obj = {
                token: user.getToken()
            }
            getFontList(obj).then(response => {
                let result = response.data;
                if (result && result.state && result.state.code && result.state.code === 10000) {
                    this.$store.commit('setFontList', result.body.message);
                    if (result.body.message && result.body.message.length) {
                        this.checkFontFamily(result.body.message);
                    }
                    if (this.notFontList.length) {
                        // message.message(`缺少${this.notFontList.join(',')}字体`, 'error');
                        this.warningFontVisible = true;
                    }
                    this.notFontList = [];
                } else {
                    message.message(result.body.message, 'error');
                }
            }).catch(error => {
                console.log(error);
            });

            getTemplateList({}).then(response => {
                let result = response.data;
                if (result && result.state && result.state.code && result.state.code === 10000) {
                    let array = result.body.message.list.filter((res) => res.layout == this.layout);
                    for (let index = 0; index < array.length; index++) {
                        const element = array[index];
                        tree[7].children.push({
                            id: 'Templete',
                            clickid: element.id,
                            label: element.name,
                            icon: element.preview
                        })
                    }
                } else {
                    message.message(result.body.message, 'error');
                    tree[7].children = [];
                }
            }).catch(error => {
                console.log(error);
            });
        },
        initialize() {
            if (scene.getID() !== null) {
                let result = request.getTemplate({ token: user.getToken(), id: scene.getID() });
                if (this.$route.query.model == '1') {
                    scene.setID(null);
                }
                if (result.state.code === 10000) {
                    let { attribute } = result.body.message;
                    store.set(JSON.parse(attribute));
                } else {
                    message.message(result.state.message, 'error');
                }
                history.addHistory(store.clone(), 2);
            } else {
                let date = new Date();
                let y = date.getFullYear();
                let m = date.getMonth() + 1;
                m = m < 10 ? '0' + m : m;
                let d = date.getDate();
                d = d < 10 ? '0' + d : d;
                let h = date.getHours();
                h = h < 10 ? '0' + h : h;
                let minute = date.getMinutes();
                minute = minute < 10 ? '0' + minute : minute;
                let projectName = '' + y + m + d + h + minute;
                store.setCanvas({ name: projectName });
                history.addHistory(store.clone(), 2);
            }
            if (user.getPanel() === 'true') {
                this.$store.commit('setEnableInteract', true);
            }
            if (shortcut.saveTime) {
                shortcut.saveProject();
            }
        },
        pageTab(value) {
            this.tabVisible = value;
        },
        autoCanvasScale() {
            let box = document.getElementById(window.getRootName() + 'SECTION_CONTENT').getBoundingClientRect();
            let width = 20; // 标尺的高度
            let scale1 = ((box.width - width) / store.getCanvas().width) * 100;
            let scale2 = ((box.height - width) / store.getCanvas().height) * 100;
            let canvas = {
                layout: this.layout,
                scale: scale1 > scale2 ? parseInt(scale2) : parseInt(scale1)
            };
            if (scale1 < 0) {
                canvas.scale = 73
            }
            store.setCanvas(canvas);
            // this.$refs.horizontalRule.addEventListener('mousemove', function(e){
            //     console.log((e.offsetX / 0.69).toFixed(0));
            // })
        },
        shadeMouseDown(e) {    
            if (status.isCanvasMove()) {
                e.stopPropagation();
                let startX = e.clientX;
                let startY = e.clientY;
                let scrollTop = this.$refs.mainCanvas.scrollTop;
                let scrollLeft = this.$refs.mainCanvas.scrollLeft;
                let _this = this;
                let move = function(e) {
                    let offsetX = scrollLeft - (e.clientX - startX);
                    let offsetY = scrollTop - (e.clientY - startY);
                    if (offsetX < 0) {
                        offsetX = 0;
                    }
                    if (offsetY < 0) {
                        offsetY = 0;
                    }
                    _this.$refs.mainCanvas.scrollTop = offsetY;
                    _this.$refs.mainCanvas.scrollLeft = offsetX;
                };
                let up = function(e) {
                    document.removeEventListener('mousemove', move);
                    document.removeEventListener('mouseup', up);
                };
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', up);
            }
        },
        setPreview(visible) {
            if (visible) {
                status.setShortcut(false);
                let state = store.clone();
                this.elementList = state.elementList;
                this.canvas = state.canvas;
                this.pageList = state.pageList;
                this.preview = true;
            } else {
                status.setShortcut(true);
                this.preview = false;
                this.elementList = [];
                this.pageList = [];
                this.canvas = {};
            }
            if (user.getPanel() === 'true') {
                this.$store.commit("setMainUIVisibility", !visible);
                let flag = this.mapActive === 0 ? false : true;
                if (visible) {
                    flag = visible;
                }
                this.$store.commit('setEnableInteract', flag);
            }
            
        },
        barClick(index) {
            if (this.navbar !== index) {
                this.navbar = index;
                this.webVisible = !this.webVisible;
                this.$store.commit('setEnableInteract', this.webVisible);
            }
            if (index === 1) {
                this.$store.commit('setMapActive', 0);
                status.setShortcut(true);
            }
        },
        getScroll(e) {
            let scrollTop = e.target.scrollTop;
            let scrollLeft = e.target.scrollLeft;
            this.scroll.top = -scrollTop + 20;
            this.scroll.left = -scrollLeft + 20;
        },
        checkFontFamily(fontList, elementList = store.getElementList()) {
            if (elementList.length) {
                for (let index = 0; index < elementList.length; index++) {
                    const element = elementList[index];
                    if (element.component === 'VText' || 
                        element.component === 'Shape' || 
                        (element.component === 'BoxModel' && element.attribute.tag ==='11') || 
                        element.component === 'Decoration' && (element.attribute.tag === '7' || element.attribute.tag === '9' || element.attribute.tag === '11') ||
                        element.component === 'Menu' ||
                        element.component === 'VButton' ||
                        element.component === 'CarouselText' ||
                        element.component === 'Time' ||
                        element.component === 'Statistic05') {
                        if (element.style.hasOwnProperty('fontFamily')) {
                            let findex = 0;
                            if (element.style.fontFamily !== 'inherit') {
                                findex = fontList.findIndex(function(value) {
                                    return value.name == element.style.fontFamily;
                                });
                            }
                            if (findex === -1) {
                                this.notFontList.push(element.style.fontFamily);
                            }
                            if (element.component === 'Group') {
                                this.checkFontFamily(fontList, element.attribute.children);
                            }
                        }
                    }
                }
            }
        }
    }
};
</script>

<style lang='scss' scoped>
.home {
    color: $white;
    background-color: #21212180;
    position: relative;
}
.toolbar-wrap {
    width: 100%;
    height: 84px;
    background-color: #000000d9;
    border-bottom: 1px solid $BorderColor;
}
.content-wrap {
    height: calc(100vh - 84px);
    position: relative;
}
.page-wrap {
    width: 240px;
    height: calc(100vh - 43px);
    background-color: #212121ff;
    border-right: 1px solid $black;
    position: absolute;
    top: -41px;
    left: 0;
    display: flex;
    flex-direction: column;
}
.main-wrap {
    height: calc(100%);
    background-color: #05090c;
    // background: $transparent;
    margin: 0 250px 0 240px;
    // padding: 2px;
    overflow: auto;
    position: relative;
    .content {
        position: relative;
        width: 100%;
        height: 100%;
        transform-origin: 0 0;
        overflow: hidden;
    }
    .content-editor {
        position: relative;
        overflow: auto;
        // transform-origin: 0 0;
        width: calc(100% - 20px);
        height: calc(100% - 20px);
        margin: 20px 0 0 20px;
    }
    .horizontal-rule {
        position: absolute;
        top: 0;
        left: 20px;
        right: 0;
        height: 20px;
        // transform-origin: 0 0;
    }
    .vertical-rule {
        position: absolute;
        top: 20px;
        left: 0;
        bottom: 0;
        width: 20px;
        // transform-origin: 0 0;
    }
}
.attribute-wrap {
    width: 250px;
    height: 100%;
    background-color: #212121ff;
    border-left: 1px solid $BorderColor;
    position: absolute;
    top: 0;
    right: 0;
}
.preview {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #444444;
    opacity: 1;
    z-index: 10;
}
.page-tab {
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #05090c;
    font-weight: 600;
    div {
        display: inline-block;
        padding: 0 20px;
        cursor: pointer;
    }
    .active {
        background-color: #000000;
    }
}
.close-button {
    position: absolute;
    width: 80px;
    height: 80px;
    background-color: rgba(33, 33, 33, 0.5);
    color: #ffffff; 
    z-index: 999;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
    right: -40px;
    top: -40px;
    cursor: pointer;
    // transition: all .5s;
	// -webkit-transition: all .5s; /* Safari */
    > i {
        position: absolute;
        bottom: 15px;
        left: 17px;
        font-size: 18px;
    }
    &:hover {
        transform: scale(1.5);
        background-color: rgba(33, 33, 33, 1);
    }
}

.page-bottom-warp {
    color: #ffffff;
    height: 40px;
    display: flex;
    align-items: center;
    position: absolute;
    width: 235px;
    left: 2px;
    bottom: 0;
    padding: 0 15px;
    border-top: 1px solid black;
}
.remove-copy {
    cursor: pointer;
    &:hover {
        color: #3662ec;
    }
}
.interactive-tab {
    position: fixed;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    &-top {
        height: 42px;
        display: flex;
        align-items: center;
        > img {
            top: -4px;
            position: relative;
        }
    }
    &-bottom {
        margin-top: 4px;
        height: 32px;
        background: #1C1C1E;
        border: 1px solid #31302D;
        border-radius: 4px;
        padding: 4px;
        display: flex;
        align-items: center;
        > span {
            width: 60px;
            height: 100%;
            cursor: pointer;
            text-align: center;
            color: rgba(255, 255, 255, 0.5);
            font-weight: 700;
            display: inline-block;
            font-size: 12px;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            &:last-child {
                margin-left: 4px;
            }
            &:hover {
                color: #FFFFFF;
                background: #323A42;
                border-radius: 2px;
            }
        }
    }
    .active {
        color: #FFFFFF;
        background: #323A42;
    }
    .active-visible {
        visibility: hidden;
    }
}
</style>